<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Tool extends CI_Controller
{
	public function __construct()
	{
        parent::__construct();
        $this->load->model(['site_model','category_model','goods_model','siteorder_model','siteproduct_model','hotproduct_model']);
    }


	public function sgoods()
	{
		$lists=file_get_contents("site.txt");
		$sites=explode("\n",$lists);
		foreach($sites as $s)
		{
			$url=str_replace("https://www.","",trim($s));
			$s=$this->site_model->search($url);
			if($s)
			{
				echo $s["id"]."\n";
				$proid=[];
				$p=$this->siteproduct_model->getspecial2($s["id"]);
				if($p):
				foreach($p as $pro)
				{
					$proid[]=$pro["productid"];
				}
				$gcount=0;
				if($proid)
				{
					
					$ids=implode(",",$proid);
                    $goods=$this->goods_model->getallgoodsids($ids);
                    foreach($goods as $good)
                    {
                        $good["catid"]=486;
                        $good["collection"]=str_replace(".com","",$url);
                        unset($good["id"]);
                        $gcount++;
                        $this->goods_model->create($good);
                    }    
				}
				echo $url." {$gcount} copy done\n";
				endif;
			}
		}
		echo "all done";
		die();
    }
    
    public function summarycate($catid)
    {
        if(empty($catid))
        {
            echo "pass the catid";
            die();
        }
        $cat = $this->category_model->getitembyid($catid);
        if(!$cat)
        {
            echo "error catid";
            die();
        }
        $config=get_system_settings();
        $alicategoey=[];
        $aliindex=[];
        if(isset($config["expresscategory"]) && $config["expresscategory"])
        {
            $rows=explode("\n",$config["expresscategory"]);
            if($rows)
            {
                foreach($rows as $row)
                {
                    if($row && strstr($row,"#"))
                    {
                        $tmp=explode("#",$row);
                        $alicategoey[]=["name"=>trim($tmp[0]),"ids"=>trim($tmp[1])];
                        if(trim($tmp[1]))
                        {
                            $mlist=explode(",",trim($tmp[1]));
                            foreach($mlist as $key)
                            {
                                $aliindex[$key]=1;
                            }
                        }
                    }
                }
            }
        }
        $alicats=$this->goods_model->getalicats($catid);
        if($alicats)
        {
            foreach($alicats as $cat)
            {

                if(!isset($aliindex[$cat["rcatid"]]))
                {
                    $aliindex[$cat["rcatid"]]=1;
                    $alicategoey[]=["name"=>$cat["rcatid"],"ids"=>$cat["rcatid"]];
                }
            }
        }

        if($alicategoey)
        {
            
            $summary=[];
            foreach($alicategoey as $ali)
            {
                $count=$this->goods_model->getalicount($catid,$ali["ids"]);
                if($count>99)
                {
                    $count2=$this->goods_model->getalicount2($catid,$ali["ids"]);
                    $summary["list"][]=["name"=>$ali["name"],"count"=>$count,"count2"=>$count2];
                }
            }
            $summary["update"]=date("Y-m-d H:i:s");
            $this->category_model->update($catid,["alisummary"=>json_encode($summary)]);
        }
        echo "job done";
        die();

    }

    public function dosite()
    {
        $sites=$this->site_model->getall();
        foreach($sites as $site)
        {
            $gcount=$this->siteproduct_model->getproductcount($site["id"]);
            $ocount=$this->siteorder_model->getordercount($site["id"]);
            $this->site_model->update($site["id"],["gcount"=>$gcount,"ocount"=>$ocount]);
            echo $site["id"]." done\n";
        }
    }

    public function fixordersync()
    {
        $count=0;
        $where=" shipping like '800%' and state=4 ";
        $orders=$this->siteorder_model->getfilter($where);
        foreach($orders as $order)
        {
            $newdata=[
                "state"=>3,
                "shipping"=>"",
                "buy_source"=>"aliexpress",
                "buy_ordersn"=>trim($order["shipping"]),
                "shipcount"=>1,
            ];
            $count++;
            $this->siteorder_model->update($order["id"],$newdata);
        }

        echo "fix ".$count." orders";
        die();
    }

    public function syncorder()
    {
        $count=0;
        $orders=$this->siteorder_model->getall();
        foreach($orders as $order)
        {
            $n=trim($order["buy_ordersn"]);
            if($n!=$order["buy_ordersn"])
            {
                $this->siteorder_model->update($order["id"],["buy_ordersn"=>$n]);
                $count++;
            }
        }
        echo "fix ".$count." orders";
        die();
    } 

    public function synccate()
    {
        $cats=$this->category_model->getall();
        foreach($cats as $item)
        {
            $newdata=[];
            $newdata["gdcount"]=$this->goods_model->getproductcount($item["id"],1);
            $newdata["gcount"]=$this->goods_model->getproductcount($item["id"]);
            $newdata["glast"]=$this->goods_model->getlasttime($item["id"]);
            $this->category_model->update($item["id"],$newdata);
        }
        die("ok");
    }

    public function formatprice()
    {

        $page=1;
        while(1)
        {
            echo "fetch page {$page} ... \n";
            $products=$this->goods_model->getallgoodbypage($page,100);

            if(empty($products))
            {
                break;
            }
            foreach($products as $p)
            {
                $price=str_replace(["us",","],"",$p["price"]);
                $format_num = sprintf("%.2f",$price);
                $this->goods_model->update($p["id"],["price"=>$format_num]);
            }
            $page++;
        }
        
        echo 'all done';
        die();
    }


    public function getprestashop()
    {
        $site=$this->site_model->getsitetype(1);
        echo json_encode($site);
        die();
    }

    public function getalllink()
    {
        $request = $this->uri->uri_to_assoc(3);
        $siteid=$request["siteid"];
        $maxid=$request["maxid"];
        $data=$this->siteproduct_model->geturls($maxid,$siteid);
        echo json_encode($data);
        die();
    }


    public function checkrids()
    {
        $info=json_decode($this->input->raw_input_stream,true);	
        $siteid=$info["siteid"];
        $rids=$info["rids"];
        $result=$this->siteproduct_model->checkrids($siteid,$rids);
        $diff = array_diff($rids,$result);
        echo json_encode($diff);
        die();
    }

    public function updatelink($siteid)
    {
        $info=json_decode($this->input->raw_input_stream,true);	
        if($info)
        {
            foreach($info as $item)
            {
                $this->siteproduct_model->updatelink($item,$siteid);
            }
        }
        echo "ok";
        die();
    }

    public function cleangoods()
	{
		$siteid=112;
		$site=$this->site_model->getitembyid($siteid);		
		loadsystemlink($site);
		if(!$this->mysite->checklink)
		{	
			echo "link error";
			die();				
		}

		$where="siteid={$siteid} and cid=6";
		$count=0;
		$goods=$this->siteproduct_model->getitemsfilter($where);
		foreach($goods as $g)
		{
			$this->mysite->delproduct(["rid"=>$g["rid"]]);
			$this->siteproduct_model->delitem($g["id"]);
			echo "delete product ".$g["productid"]."\n";
			$count++;
        }
        $gcount=$this->siteproduct_model->getproductcount($siteid);
        $this->site_model->update($site["id"],["gcount"=>$gcount]);
		echo "del {$count} products ";
		die();
    }


    public function cleannosellgoods()
	{
		$siteid=104;
		$site=$this->site_model->getitembyid($siteid);		
		loadsystemlink($site);
		if(!$this->mysite->checklink)
		{	
			echo "link error";
			die();				
		}

		$where="siteid={$siteid} and sellcount=0";
		$count=0;
		$goods=$this->siteproduct_model->getitemsfilter($where);
		foreach($goods as $g)
		{
			$this->mysite->delproduct(["rid"=>$g["rid"]]);
			$this->siteproduct_model->delitem($g["id"]);
			echo "delete product ".$g["productid"]."\n";
			$count++;
        }
        $gcount=$this->siteproduct_model->getproductcount($siteid);
        $this->site_model->update($site["id"],["gcount"=>$gcount]);
		echo "del {$count} products ";
		die();
    }

    

    public function calue()
    {
        $orders=$this->siteorder_model->gettongji();
        if($orders):
        foreach($orders as $order)
        {
            $products=json_decode($order["productinfo"],true);
            foreach($products as $pro)
            {
                $pro["siteid"]=$order["siteid"];
                $pro["addtime"]=$order["addtime"];
                $pro["price"]=sprintf("%.2f",$pro["price"]);
                $this->hotproduct_model->addsell($pro);              
            }
            $this->siteorder_model->update($order["id"],["tongji"=>1]);
        }
        endif;

        $orders=$this->siteorder_model->getcancel();
        if($orders):
        foreach($orders as $order)
        {
            $products=json_decode($order["productinfo"],true);
            foreach($products as $pro)
            {
                $pro["siteid"]=$order["siteid"];
                $pro["addtime"]=$order["addtime"];
                $pro["price"]=sprintf("%.2f",$pro["price"]);
                $this->hotproduct_model->decsell($pro);              
            }
            $this->siteorder_model->update($order["id"],["tongji"=>0]);
        }
        endif;

        die("ok");
    }


    public function errorprice()
	{
		$siteproduct=[];
		$where="price like 'from%'";
		$goods=$this->goods_model->get_items_by_where_fix($where);
		foreach($goods as $product)
		{
			
			$product["price"]=str_replace("\n",".",trim(str_replace("from","",$product["price"])));
			echo $product["id"].":".$product["price"]."\n"; 
			$sg=$this->siteproduct_model->getitemsfilter(["productid"=>$product["id"]]);
			if($sg){
				foreach($sg as $g)
				{
					$product["rid"]=$g["rid"];
					$product["ogid"]=$g["id"];
					$siteproduct[$g["siteid"]][]=$product;
				}
			}
			$this->goods_model->update($product["id"],["price"=>$product["price"]]);
		}
		$gcount=0;
		foreach($siteproduct as $siteid=>$v)
		{
			
			$site=$this->site_model->getitembyid($siteid);
			$this->load->library('sitetype/prestashop',$site,'mysite');	
			foreach($v as $g)
			{
				$newprice = get_price($site["ruler"],$g["price"]);
				$result = $this->mysite->updatepro($g["rid"],["price"=>$newprice]);
				$this->siteproduct_model->update($g["ogid"], ["price"=>$newprice]);
				echo "new price :".$newprice."\n";
				$gcount++;
			}
			
			unset($this->mysite);
		}
		echo $gcount." goods price update";
		die("ok");
    }
    

    public function fix_combine()
    {
        $priceruler = '0-4.99:plus#17||5-9.99:formula#$price*4+7||10-14.99:formula#$price*3.5+7||15-19.99:formula#$price*3+7||20-29.99:formula#$price*2.5+7||def:formula#$price*1.9+7';

        $sites=$this->site_model->getsitetype(1);
        foreach($sites as $site)
        {
            if($site["id"]>=91)
            {
                continue;
            }
            echo "开始检查站点".$site["name"].",共有".$site["gcount"]."件产品\n";
            loadsystemlink($site);
            $page=1;
            while(1)
            {
                echo "检查第{$page}页产品...\n";
                $sps=$this->siteproduct_model->getpidbypage($site["id"],$page);
                if($sps)
                {
                    $productinfo=$this->goods_model->getcombinegoods($sps);
                    if($productinfo)
                    {
                        $fixcount=$existcount=$noneprocount=0;
                        echo "发现 ".count($productinfo)." 条待更新产品\n";
                        foreach($productinfo as $good)
                        {

                            $good["price"]=get_price($priceruler,$good["price"]);
                            foreach($good["option"]["vv"] as $k=>$option){
                                if(!empty($option["image"]))
                                {
                                    $hasimg=true;
                                }
                                if(strstr(strtolower($option["name"]),"color") || strstr(strtolower($option["name"]),"colour"))
                                {
                                    $good["option"]["vv"][$k]["name"]="Color";
                                }
                                if(strstr(strtolower($option["name"]),"size"))
                                {
                                    $good["option"]["vv"][$k]["name"]="Size";
                                }
                                if(isset($option["price"]))
                                {
                                    foreach($option["price"] as $k1=>$v1)
                                    {
                                        $v1=str_replace([",","$"],"",$v1);
                                        $good["option"]["vv"][$k]["price"][$k1]=get_price($priceruler,$v1);
                                    }
                                }
                            }

                            $good["sku"]=$site["sku"]."_".$good["id"];
                            $result=$this->mysite->fixcombine($good);      
                            if($result=="ok")
                            {
                                $fixcount++;
                            }
                            elseif($result=="1")
                            {
                                $noneprocount++;
                            }
                            elseif($result=="2")
                            {
                                $existcount++;
                            }
                        }
                        echo "成功更新 ".$fixcount." 件,已有变体 ".$fixcount." 件,未找到商品 ".$noneprocount." 件 \n";
                    }

                    $page++;
                }
                else
                {
                    break;
                }
            }
            echo "站点".$site["name"]."检查完毕\n\n";
            unset($this->mysite);
        }

    }

}
